package com.nidu.demo.web.system;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.permission.api.SysPermissionService;
import com.nidu.demo.security.util.SecurityUtils;
import com.nidu.demo.user.api.SysUserService;
import com.nidu.demo.user.dto.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

/**
 * 用户个人中心 Controller
 */
@Tag(name = "管理后台 - 用户个人中心")
@RestController
@RequestMapping("/system/user")
@Validated
@RequiredArgsConstructor
public class SysUserProfileController {

    private final SysUserService service;

    private final SysPermissionService permissionService;

    @GetMapping("/permissions")
    @Operation(summary = "获取用户的权限信息")
    public SingleResponse<UserPermissionInfoCO> getPermissionInfo() {
        return permissionService.getPermissionInfo(SecurityUtils.getLoginUserId());
    }

    @GetMapping("/profile")
    @Operation(summary = "获取用户详情", description = "根据 ID 获取用户详细信息")
    public SingleResponse<UserProfileCO> getUserProfile() {
        return service.getProfileById(SecurityUtils.getLoginUserId());
    }

    @PutMapping("/profile")
    @Operation(summary = "修改用户个人信息")
    public Response updateUserProfile(@Valid @RequestBody UserUpdateProfileCmd cmd) {
        return service.updateProfile(SecurityUtils.getLoginUserId(), cmd);
    }

    @PutMapping("/profile/password")
    @Operation(summary = "修改用户个人密码")
    public Response updateUserProfilePassword(@Valid @RequestBody UserUpdatePasswordCmd cmd) {
        return service.updatePassword(SecurityUtils.getLoginUserId(), cmd);
    }

    @PutMapping(value = "/profile/avatar")
    @Operation(summary = "上传用户个人头像")
    public SingleResponse<String> updateUserAvatar(@RequestParam("avatarFile") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new BizException(ErrorCodeConstants.BAD_REQUEST.getCode(), "上传个人头像文件为空");
        }
        return service.updateAvatar(SecurityUtils.getLoginUserId(), file.getInputStream());
    }

}